<?php
/**
 * Introduction: 商品sku表  product_sku
 */

namespace Common\Model;

use Think\Model;

class ProductSkuModel extends Model
{
    //定义数据库连接信息
    protected $connection;

    //定义表名
    protected $tableName = 'product_sku';

    /**
     * 初始化
     */
    public function _initialize()
    {

        $this->connection = C('Databaese');

    }


    /**
     * 商品关键词（商品列表）
     */
    public function keyword_search($keyword,$num,$limit,$stock_id,$cat_id,$xinpin,$sale,$price){
        $fields = ['ps.id','ps.pid','ps.pname','ps.promotion_tips','ps.pic','ps.stock_shop','ps.ms_stock_supplierid', 'ps.ms_entrepot_supplierid', 'ps.ms_direct_supplierid', 'ps.ms_price', 'ps.price', 'ps.market_price', 'ps.ms_discount', 'ps.status', 'ps.sell_amount', 'ps.guojia', 'ps.guojiapic'];
        $order = '';
        $where = "";
        if($sale){
            $order = " sale $sale";
        }
        if($xinpin){
            $order = " create_time $xinpin";
        }
        if($price){
            $order = " ms_price $xinpin";
        }
        if($stock_id){
            $where .= " and stock_shop=$stock_id";
        }
        if($cat_id){
            $where .= " and catid like '$cat_id%'";
        }
        if($keyword){
            $list = $this->alias("ps")->where("ps.pname like '%$keyword%' and ps.status > 0 $where  and ps.miaosha_type=0 and ps.catId!=1011")->field($fields)->order($order)->limit("$num,$limit")->select();
        }else{
            $list = $this->alias("ps")->where("ps.status > 0 $where  and ps.miaosha_type=0 and ps.catId!=1011")->field($fields)->order($order)->limit("$num,$limit")->select();
        }
        $stock_shop = [];
        foreach($list as $k=>$v){
            $stock_shop[] = $v['stock_shop'];
            $ways = [];
            $way = $this->getShipmentsWay($v['id'], 1, $v['ms_stock_supplierid']);
            if (!empty($way)) {
                $ways[] = $way;
            }

            //是否存在于保税仓库
            $warehouseType = 1;
            $way = $this->getShipmentsWay($v['id'], 2, $v['ms_entrepot_supplierid']);
            if (!empty($way)) {
                $ways[] = $way;
            }

            //是否存在于直邮仓
            $warehouseType = 1;
            $way = $this->getShipmentsWay($v['id'], 3, $v['ms_direct_supplierid']);
            if (!empty($way)) {
                $ways[] = $way;
            }
            $pic = explode(',',$v['pic']);
            $list[$k]['pic'] = $pic[0];
            $list[$k]['supplierId'] = $ways[0]['supplierId'];
            $list[$k]['stock'] = $ways[0]['stock'];
            $list[$k]['warehouseType'] = $ways[0]['warehouseType'];
        }
        if($stock_shop){
            $stock_id = join(',',$stock_shop);
            $model = new StockShopsModel();
            $stock_list = $model->where("id in ($stock_id)")->field("id,title")->select();
        }
        $res['list'] = $list;
        $res['stock_list'] = $stock_list;
        return $res;
    }

    /**
     * 获取中国商品
     *
     */
    public function guojia_goods_list($guojia,$num,$limit){
        $fields = ['ps.id','ps.pid','ps.pname','ps.promotion_tips','ps.pic','ps.stock_shop','ps.ms_stock_supplierid', 'ps.ms_entrepot_supplierid', 'ps.ms_direct_supplierid', 'ps.ms_price', 'ps.price', 'ps.market_price', 'ps.ms_discount', 'ps.status', 'ps.sell_amount', 'ps.guojia', 'ps.guojiapic'];
        if($guojia){
            $list = $this->alias("ps")->where("ps.status > 0 and guojia='$guojia'  and ps.miaosha_type=0 and ps.catId!=1011")->field($fields)->limit("$num,$limit")->select();

        }else{
            $list = $this->alias("ps")->where("ps.status > 0 and guojia='中国'  and ps.miaosha_type=0 and ps.catId!=1011")->field($fields)->limit("$num,$limit")->select();

        }
        foreach($list as $k=>$v){
            $ways = [];
            $way = $this->getShipmentsWay($v['id'], 1, $v['ms_stock_supplierid']);
            if (!empty($way)) {
                $ways[] = $way;
            }

            //是否存在于保税仓库
            $warehouseType = 1;
            $way = $this->getShipmentsWay($v['id'], 2, $v['ms_entrepot_supplierid']);
            if (!empty($way)) {
                $ways[] = $way;
            }

            //是否存在于直邮仓
            $warehouseType = 1;
            $way = $this->getShipmentsWay($v['id'], 3, $v['ms_direct_supplierid']);
            if (!empty($way)) {
                $ways[] = $way;
            }
            $pic = explode(',',$v['pic']);
            $list[$k]['pic'] = $pic[0];
            $list[$k]['supplierId'] = $ways[0]['supplierId'];
            $list[$k]['stock'] = $ways[0]['stock'];
            $list[$k]['warehouseType'] = $ways[0]['warehouseType'];
        }
        return $list;
    }

    /**
     * 获取品牌商品
     *
     */
    public function brand_goods_list($id,$num,$limit){
        $fields = ['ps.id','ps.pid','ps.pname','ps.promotion_tips','ps.pic','ps.stock_shop','ps.ms_stock_supplierid', 'ps.ms_entrepot_supplierid', 'ps.ms_direct_supplierid', 'ps.ms_price', 'ps.price', 'ps.market_price', 'ps.ms_discount', 'ps.status', 'ps.sell_amount', 'ps.guojia', 'ps.guojiapic'];
        if($id){
           return  $list = $this->alias("ps")->where("ps.status > 0 and brandid='$id'  and ps.miaosha_type=0 and ps.catId!=1011")->field($fields)->limit("$num,$limit")->select();

        }else{
            $list = [];
        }
        foreach($list as $k=>$v){
            $ways = [];
            $way = $this->getShipmentsWay($v['id'], 1, $v['ms_stock_supplierid']);
            if (!empty($way)) {
                $ways[] = $way;
            }

            //是否存在于保税仓库
            $warehouseType = 1;
            $way = $this->getShipmentsWay($v['id'], 2, $v['ms_entrepot_supplierid']);
            if (!empty($way)) {
                $ways[] = $way;
            }

            //是否存在于直邮仓
            $warehouseType = 1;
            $way = $this->getShipmentsWay($v['id'], 3, $v['ms_direct_supplierid']);
            if (!empty($way)) {
                $ways[] = $way;
            }
            $pic = explode(',',$v['pic']);
            $list[$k]['pic'] = $pic[0];
            $list[$k]['supplierId'] = $ways[0]['supplierId'];
            $list[$k]['stock'] = $ways[0]['stock'];
            $list[$k]['warehouseType'] = $ways[0]['warehouseType'];
        }
        return $list;
    }
    /**
     * 商品列表
     */
    public function lists($catId,$num,$limit){
        $fields = ['ps.id','ps.pid','ps.pname','ps.promotion_tips','ps.pic','ps.stock_shop','ps.ms_stock_supplierid', 'ps.ms_entrepot_supplierid', 'ps.ms_direct_supplierid', 'ps.ms_price', 'ps.price', 'ps.market_price', 'ps.ms_discount', 'ps.status', 'ps.sell_amount', 'ps.guojia', 'ps.guojiapic'];

        if($catId){
            $list = $this->alias("ps")->where("ps.catId like '$catId%' and ps.status > 0 and ps.miaosha_type=0 and ps.catId!=1011")->field($fields)->limit("$num,$limit")->select();
        }else{
            $list = $this->alias("ps")->where("ps.status > 0  and ps.miaosha_type=0 and ps.catId!=1011")->field($fields)->limit("$num,$limit")->select();
        }
        foreach($list as $k=>$v){
            $ways = [];
            $way = $this->getShipmentsWay($v['id'], 1, $v['ms_stock_supplierid']);
            if (!empty($way)) {
                $ways[] = $way;
            }

            //是否存在于保税仓库
            $warehouseType = 1;
            $way = $this->getShipmentsWay($v['id'], 2, $v['ms_entrepot_supplierid']);
            if (!empty($way)) {
                $ways[] = $way;
            }

            //是否存在于直邮仓
            $warehouseType = 1;
            $way = $this->getShipmentsWay($v['id'], 3, $v['ms_direct_supplierid']);
            if (!empty($way)) {
                $ways[] = $way;
            }
            $pic = explode(',',$v['pic']);
            $list[$k]['pic'] = $pic[0];
            $list[$k]['supplierId'] = $ways[0]['supplierId'];
            $list[$k]['stock'] = $ways[0]['stock'];
            $list[$k]['warehouseType'] = $ways[0]['warehouseType'];
        }
        return $list;
    }



    /**
     * 获取发货方式
     * @param unknown $skuId
     * @param unknown $warehouseType
     * @param unknown $supplierId
     */
    public function getShipmentsWay($skuId, $warehouseType, $supplierId)
    {
        if ($supplierId < 0) {
            return [];
        }

        //限制数量

        $skuInfo = $this->getInfoById($skuId);
        $buyLimit = $skuInfo->buy_limit;;
        if ($warehouseType != '3') {
            //非直邮，使用微店限购
            $buyLimit = $skuInfo->ms_buy_limit;
        }

        //配送方名称
        if ($supplierId == 0) {
            //自营
            $stockShopId = 0;
            $stock = 0;
            switch ($warehouseType) {
                case '1' :
                    //自营现货，只有成都仓
                    $stockShopId = 20;
                    break;
                case '2':
                    //自营保税仓只有广州保税仓
                    $stockShopId = 15;
                    break;
                case '3':
                    //自营直邮直接使用库存里面记录的id
                    $stockShopId = $skuInfo['stock_shop'];
                    break;
            }
            $stockModel = new StockShopsModel();
            $stockShopInfo = $stockModel->getInfoById($stockShopId);
            $name = $stockShopInfo['show_title'];
        } elseif ($supplierId > 0) {
            //第三方
            $model = new StockSuppliersModel();
            $stockShopInfo = $model->getStockShopInfoById($supplierId);
            $name = $stockShopInfo['show_title'];
        }

        $stock = $this->getProductStock($skuId, $warehouseType, $supplierId);
        $ways = ['warehouseType' => $warehouseType ,'supplierId' => $supplierId, 'name' => $name, 'buyLimit' => $buyLimit,'stock' => $stock,'logisticsId'=>$stockShopInfo['logisticsId']];
        return $ways;
    }

    /**
     * 获取商品真实库存
     * @param unknown $skuId
     * @param unknown $warehouseType
     * @param unknown $supplierId
     */
    public function getProductStock($skuId, $warehouseType, $supplierId)
    {
        if ($supplierId < 0) {
            //不支持此方式
            $stock = 0;
        } elseif ($supplierId > 0) {
            //第三方供应商，判断其供应库存是否充足
            $model = new StockSupplieProductsModel();
            $stock = $model->getStock($skuId, $supplierId);
        } else {
            //自营
            if ($warehouseType == '1') {
                //国内现货库存，只有成都仓
                $stockShopId = 20;
                $model = new StockStocksModel();
                $stock = $model->getStocksByShopIdWithProductId($stockShopId, $skuId);
            } elseif($warehouseType == '2') {
                //保税仓
                $stockShopId = 15;
                $model = new StockStocksModel();
                $stock = $model->getStocksByShopIdWithProductId($stockShopId, $skuId);
            } else {
                //直邮
                $skuInfo = $this->getInfoById($skuId);
                $stock = $skuInfo['stock'];
                $stockShopId = $skuInfo['stock_shop'];
            }
            //非直邮减去待出库的数量
            if ($warehouseType != '3') {
                $model = new StockStocksModel();
                $stock = $stock - $model->getSoldNum($stockShopId, $skuId);
            }
        }
        return $stock;
    }

    /**
     * 获取商品详细
     */

    public function getRow($id){
        $fields = ['ps.id','ps.pid','ps.pname','ps.pic','ps.ms_price','ps.market_price','ps.ms_status','ps.status','ps.stock','ps.stock_shop',
            'ps.buy_limit','ps.ms_buy_limit','ps.sell_amount','ps.spec', 'ps.ms_stock_supplierid', 'ps.ms_entrepot_supplierid',
            'ps.ms_direct_supplierid','ps.ms_taxation','ps.sale','ps.thing_num','p.detail','ps.video','ps.guojia','ps.guojiapic'];
        $info = $this->alias('ps')->join("haiou_products as p on ps.pid=p.id")->where("ps.id=$id")->field($fields)->find();
        $model = new OrderProductModel();
        $count = $model->where("product_id=".$info['id'])->count();
        $info['sale'] = $info['sale']+$count;
        $info['pic'] = explode(',',$info['pic']);
        $ways = [];
        $way = $this->getShipmentsWay($info['id'], 1, $info['ms_stock_supplierid']);
        if (!empty($way)) {
            $ways[] = $way;
        }

        //是否存在于保税仓库
        $warehouseType = 1;
        $way = $this->getShipmentsWay($info['id'], 2, $info['ms_entrepot_supplierid']);
        if (!empty($way)) {
            $ways[] = $way;
        }

        //是否存在于直邮仓
        $warehouseType = 1;
        $way = $this->getShipmentsWay($info['id'], 3, $info['ms_direct_supplierid']);
        if (!empty($way)) {
            $ways[] = $way;
        }
        $info['supplierId'] = $ways[0]['supplierId'];
        $info['stock'] = $ways[0]['stock'];
        $info['warehouseType'] = $ways[0]['warehouseType'];
        return $info;
    }
    /**
     * 获取商品详情
     * @param unknown $id
     */
    public function getInfoById($id){
        $fields = ['id','pid','pname','pic','ms_price','market_price','ms_status','status','stock','stock_shop',
            'buy_limit','ms_buy_limit','sell_amount','spec', 'ms_stock_supplierid', 'ms_entrepot_supplierid',
            'ms_direct_supplierid','ms_taxation'];
        $info = $this->where("id=$id")->field($fields)->find();
        return $info;
    }

    /**
     * 赞商品
     */
    public function zan($id){
        $info = $this->where("id=$id")->field("thing_num")->find();
        $sale = $info['thing_num'] + 1;
        $this->where("id=$id")->save(['thing_num'=>$sale]);
        $info = $this->where("id=$id")->field("thing_num")->find();
        return $info['thing_num'];
    }

    /**
     * 取消赞
     */
    public function clear_zan($id){
        $info = $this->where("id=$id")->field("thing_num")->find();
        $sale = $info['thing_num'] - 1;
        if($sale<=0){
            $sale = 0;
        }
        $this->where("id=$id")->save(['thing_num'=>$sale]);
        $info = $this->where("id=$id")->field("thing_num")->find();
        return $info['thing_num'];
    }

    /**
     * 更新商品库存和销量
     * @param unknown $stockShopId
     * @param unknown $skuId
     * @param unknown $num
     */
    public function updateStocksAndSellAmount($stockShopId,$skuId,$num){
        $info = $this->where("id=$skuId and stock_shop=$stockShopId")->field("stock,sell_amount")->find();
        $stock = $info['stock']+$num;
        $sell_amount = $info['sell_amount']-$num;
        $res = $this->where("id=$skuId and stock_shop=$stockShopId")->save(['stock'=>$stock,'sell_amount'=>$sell_amount]);

        return ($res)?true:false;
    }
}